<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" draggable>
    <el-form ref="formRef" style="max-width: 600px" :rules="rules" :model="form" label-width="auto" class="demo-dynamic">
      <el-form-item prop="oldPassword" label="旧密码">
        <el-input v-model="form.oldPassword" show-password />
      </el-form-item>
      <el-form-item prop="newPassword" label="新密码">
        <el-input v-model="form.newPassword" show-password />
      </el-form-item>
      <el-form-item prop="newPassword1" label="确认新密码">
        <el-input v-model="form.newPassword1" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { resetUserPassWord } from "@/api/modules/user";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage } from "element-plus";
import { LOGIN_URL } from "@/config";

const router = useRouter();
const userStore = useUserStore();
const form = reactive<{
  oldPassword: string;
  newPassword: string;
  newPassword1: string;
}>({
  oldPassword: "",
  newPassword: "",
  newPassword1: ""
});
const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const validateNewPassword1 = (rule, value, callback) => {
  if (value !== form.newPassword) {
    callback(new Error("两次密码不一致!"));
  } else {
    callback();
  }
};
const rules = reactive({
  newPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 1,
      max: 16,
      message: "长度为1-16位",
      trigger: "blur"
    }
  ],
  oldPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 1,
      max: 16,
      message: "长度为1-16位",
      trigger: "blur"
    }
  ],
  newPassword1: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 1,
      max: 16,
      message: "长度为1-16位",
      trigger: "blur"
    },
    { required: true, trigger: "blur", validator: validateNewPassword1 }
  ]
});
const openDialog = () => {
  dialogVisible.value = true;
};
const handleSubmit = () => {
  formRef.value?.validate(valid => {
    if (valid) {
      resetUserPassWord(form).then(res => {
        userStore.setToken("");
        router.replace(LOGIN_URL);
        ElMessage.success("修改成功,请重新登录！");
      });
      console.log("submit!", form);
    } else {
      return false;
    }
  });
};

defineExpose({ openDialog });
</script>
